package pc.system;

import java.util.*;
import pc.util.*;

public class WTimer extends Thread
{
  private boolean terminated = false;
  private boolean done = false;
  private Calendar now = null;

  public WTimer()
  {
    super();
  }


  public void terminate()
  {
    terminated = true;
    while (!done) Utils.sleep(100);
  }

  private boolean sleep(int sec)
  {
    int count = 0;
    while (!terminated) {
      Utils.sleep(1000);
      count++;
      if (count == sec) return true;
    }
    return false;
  }

  private synchronized void checkTimeOut(int sec)
  {
    Enumeration e = WServlet.getUserList().elements();
    java.util.Date now = new java.util.Date();
    Vector rList = new Vector();
    while (e.hasMoreElements()) {
      Auth usr = (Auth)e.nextElement();
      long dt = (now.getTime() - usr.act_at.getTime())/1000;
      if (dt >= sec) {
        rList.addElement(usr);
        usr.timeout();
        System.out.println("Second passed = " + dt);
      }
    }
    for (int i = 0; i < rList.size(); i++) {
      Auth usr = (Auth)rList.get(i);
      WServlet.getUserList().remove(usr.getuid());
    }
  }

  public void run()
  {
    terminated = false;
    done = false;
    System.out.println("Auth Timer Started");
    int cur_hour = 0;
    while (!terminated && sleep(30)) {

      checkTimeOut(60*60);

      now = Calendar.getInstance();
      if (now.get(Calendar.HOUR) != cur_hour) {
        cur_hour = now.get(Calendar.HOUR);
        System.out.println("WServlet Now is " + Utils.getCurTime());
      }
    }
    done = true;
  }
}

